package com.cnb.telepathytalk.packet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

public class TelepathyPacketUtil {
	public static final String CAHRSET = "UTF-16LE";

	public static byte[] getTotalByte(byte[]... data) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try {
			for (byte[] i : data)
				baos.write(i);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return baos.toByteArray();
	}

	public static byte[] stringToByte(String str, byte[] desk) {
		desk = Arrays.copyOf(str.getBytes(Charset.forName(CAHRSET)), desk.length);
		return desk;
	}

	public static String byteToString(byte[] data) {
		int nullIndex = data.length;
		for (int i = 0; i < data.length - 1; i += 2) {
			if (data[i] == 0 && data[i + 1] == 0) {
				nullIndex = i;
				break;
			}
		}
		data = Arrays.copyOfRange(data, 0, nullIndex);
		return new String(data, Charset.forName(CAHRSET));
	}

	public static byte[] intToByte(int n, byte[] desk) {
		desk[0] = (byte) (n >>> 0);
		desk[1] = (byte) (n >>> 8);
		desk[2] = (byte) (n >>> 16);
		desk[3] = (byte) (n >>> 24);
		return desk;
	}

	public static int byteToInt(byte[] desk) {
		return (desk[3] & 0xff) << 24 | (desk[2] & 0xff) << 16 | (desk[1] & 0xff) << 8 | (desk[0] & 0xff);
	}

	public static Integer[] byteToIntArray(byte[] desk) {
		Integer[] temp = new Integer[desk.length / 4];
		for (int i = 0; i < temp.length; i++) {
			temp[i] = byteToInt(Arrays.copyOfRange(desk, i * 4, (i + 1) * 4));
		}
		return temp;
	}

	public static int getIntPacketType(int type, int subtype) {
		return type * 1000 + subtype;
	}

	public static String getStringPacketType(int type, int subtype) {
		return "PT-" + type + " ST-" + subtype;
	}
}